import React, { useState, useRef } from 'react'
import 'braft-editor/dist/index.css'
import { Form, Input, Button, Tabs, Affix, Modal, Row, Col, message, Select } from 'antd'
import BraftEditor from 'braft-editor'
import UploadCom, { putObject } from '~/components/my-upload'
import { ContentUtils } from 'braft-utils'
import { handlePosting, handleReplayPost } from '~/api/qa-api'
import styled from 'styled-components'
import { PictureOutlined } from '@ant-design/icons'
import { Upload } from 'antd'
import Draggable from 'react-draggable'

const { Option } = Select;

const DraftWrapper = styled.div`
  height: 300px;
  width: 100%;
  .bf-content {
    height: 100%;
  }
  img {
    width: 100px;
    height: 100px;
  }
`

const RichTextModal = ({
  visible,
  onCancel,
  form,
  fetchQueryReplyList,
  isPost,
  fetchQueryPostList,
  postId,
  refReplyId,
  isReply
}: any) => {
  const [editorState, setEditorState] = useState<any>(BraftEditor.createEditorState(null))
  const [disabled, setDisabled] = useState(true)
  const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 })
  const handleChange = (editorState: any) => {
    setEditorState(editorState)
  }
  const draggleRef = useRef(null)

  const extendControls: any = [
    {
      key: 'antd-uploader',
      type: 'component',
      text: '上传图片或视频',
      component: (
        // <Upload accept="image/*" showUploadList={false} customRequest={uploadHandler}>
        //   {/* 这里的按钮最好加上type="button"，以避免在表单容器中触发表单提交，用Antd的Button组件则无需如此 */}
        //   <button type="button" className="control-item button upload-button" data-title="插入图片">
        //     <PictureOutlined />{' '}
        //   </button>
        // </Upload>
        <UploadCom
          frontend="frontendeimg"
          onSuccess={({ storeId, name, files, imgUrl }: any) => {
            console.log('files', files, imgUrl, editorState)
            setEditorState(
              ContentUtils.insertMedias(editorState, [
                {
                  type: /image/.test(files.type) ? 'IMAGE' : 'AUDIO',
                  url: imgUrl
                }
              ])
            )
            // docs.set(files.name, { storeId, name })
          }}
          onRemove={(file: any) => {
            // docs.delete(file.name)
            console.log('onRemove', file)
          }}
          showUploadList={false}
        >
          {' '}
          <button type="button" className="control-item button upload-button" data-title="上传图片或视频">
            <PictureOutlined />{' '}
          </button>{' '}
        </UploadCom>
      )
    }
  ]

  const onStart = (event: any, uiData: any) => {
    const { clientWidth, clientHeight } = window?.document?.documentElement
    const targetRect = (draggleRef?.current as any)?.getBoundingClientRect()
    setBounds({
      left: -targetRect?.left + uiData?.x,
      right: clientWidth - (targetRect?.right - uiData?.x),
      top: -targetRect?.top + uiData?.y,
      bottom: clientHeight - (targetRect?.bottom - uiData?.y)
    })
  }

  const onClickSaveItems = async () => {
    const { getFieldsValue, resetFields } = form
    const { postTitle, caseNo, questionType } = getFieldsValue()
    if (editorState.toHTML() === '<p></p>') {
      return message.warn('发帖内容不能为空')
    }
    if (isPost) {
      if (!postTitle) {
        return message.warn('标题不能为空')
      }
      if (!questionType) {
        return message.warn('请选择提问类型')
      }
      if (questionType === 'OPT' && !caseNo) {
        return message.warn('案件编号不能为空')
      }
      await handlePosting({
        postTitle,
        questionType,
        caseNo,
        postContent: editorState.toHTML().replace(/<[^>]+>/g, ''),
        postContentHtml: editorState.toHTML()
      })
      fetchQueryPostList({})
    } else {
      await handleReplayPost({
        postId,
        refReplyId,
        replyContent: editorState.toHTML().replace(/<[^>]+>/g, ''),
        replyContentHtml: editorState.toHTML()
      })
      fetchQueryReplyList()
    }
    onCancel()
    resetFields()
    setEditorState('')
  }

  const controls: any = ['undo', 'redo', 'emoji', 'link', 'code', 'clear']

  return (
    <div>
      <Modal
        maskClosable={false}
        title={
          <div
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false)
              }
            }}
            onMouseOut={() => {
              setDisabled(true)
            }}
          >
            我要{isReply ? '回' : '发'}帖
          </div>
        }
        width={800}
        className="caiji-modal"
        visible={visible}
        okText="发表"
        cancelText="取消"
        onOk={onClickSaveItems}
        destroyOnClose={true}
        onCancel={onCancel}
        modalRender={modal => (
          <Draggable disabled={disabled} bounds={bounds} onStart={(event, uiData) => onStart(event, uiData)}>
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
        // {...(isView ? { footer: null } : {})}
      >
        <Form form={form} validateTrigger="onBlur" style={{ marginBottom: 16 }} className="modal-form">
          <Row>
            {!isReply && (
              <Form.Item style={{ width: '49%', marginRight: '1%' }} name="postTitle" label="标题">
                <Input placeholder="请输入标题，限制长度5-35" minLength={5} maxLength={35} style={{ width: '100%' }} />
              </Form.Item>
            )}
            {!isReply && (
              <Form.Item style={{ width: '50%' }} name="caseNo" label="案件编号">
                <Input placeholder="请输入案件编号" style={{ width: '100%' }} />
              </Form.Item>
            )}
            {!isReply && (
              <Form.Item style={{ width: '100%' }} name="questionType" label="提问类别">
                <Select
                  placeholder="请选择提问类别"
                  allowClear
                >
                  <Option value="OPT">操作问题</Option>
                  <Option value="SUGGEST">优化建议</Option>
                </Select>
              </Form.Item>
            )}
            <DraftWrapper>
              <BraftEditor
                value={editorState}
                onChange={handleChange}
                controls={controls}
                extendControls={extendControls}
              />
            </DraftWrapper>
          </Row>
        </Form>
      </Modal>
    </div>
  )
}

export default RichTextModal
